package com.newland.esp.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newland.esp.common.util.DataResult;
import com.newland.esp.entity.user.AdminInfoEntity;
import com.newland.esp.entity.user.AuthInfoEntity;
import com.newland.esp.entity.user.AuthMenuEntity;
import com.newland.esp.entity.user.UserAuthEntity;
import com.newland.esp.mapper.user.AdminInfoMapper;
import com.newland.esp.mapper.user.AuthInfoMapper;
import com.newland.esp.mapper.user.AuthMenuMapper;
import com.newland.esp.mapper.user.UserAuthMapper;
import com.newland.esp.service.user.AdminInfoService;
import com.newland.esp.vo.response.user.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @param
 * @author lw
 * @descripe
 * @date 2021/8/17 21:37
 * @Version 1.0
 **/
@Service
public class AdminInfoServiceImpl extends ServiceImpl<AdminInfoMapper,AdminInfoEntity> implements AdminInfoService {

    @Resource
    AdminInfoMapper adminInfoMapper;
    @Resource
    AuthInfoMapper authInfoMapper;
    @Resource
    UserAuthMapper userAuthMapper;
    @Resource
    AuthMenuMapper authMenuMapper;

    @Override
    public DataResult setUserIdByRoleId(Short id,Short roleId) {
        Integer integer = authInfoMapper.setUserId(id, roleId);
        if (integer != null){
            return DataResult.success();
        }
        return DataResult.error();
    }

    @Override
    public DataResult GetAllAuth() {
        List<UserAuthEntity> userAuthEntity = authInfoMapper.GetAllAuth();
        return DataResult.success(userAuthEntity);
    }

    /**
     * 查询所用用户信息 (条件查询带分页)
     * layui模板的要求返回状态码0 表示成功
     * 新建一个TableDataVo 按前端要求(code,msg,count,data(List))发送数据
     * @param page
     * @param limit
     * @return
     */
    // @RequestBody请求体为Json required = false可以为空
    @Override
    public TableDataVO<AdminInfoEntity> findAdminInfo(Integer page, Integer limit,
      @RequestBody(required = false) AdminInfoSearchVO adminInfoSearchVO) {

//        List<AdminInfoEntity> adminInfoLists = adminInfoMapper.selectList(null);
        //使用mybatisPlus 自带的分页工具查List  也可以查到记录getRecords 和记录数getTotal

        IPage<AdminInfoEntity> adminInfoEntityIPage = new Page<>(page,limit);

        //构建条件
        Short userId=null;
        String userName="";
        Date startTime=null;
        Date endTime=null;
        QueryWrapper<AdminInfoEntity> wrapper = new QueryWrapper<>();
        if(adminInfoSearchVO != null){

            userId = adminInfoSearchVO.getUserId();//用户id
            userName = adminInfoSearchVO.getUserName();//用户名
            startTime = adminInfoSearchVO.getStartTime();
            endTime = adminInfoSearchVO.getEndTime();
        }
        if(userId != null) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(userName)) {
            wrapper.like("user_name",userName);
        }
        if(startTime != null) {
            wrapper.ge("create_time",startTime);
        }
        if(endTime != null) {
            wrapper.le("update_time",endTime);
        }

        IPage<AdminInfoEntity> result = adminInfoMapper.selectPage(adminInfoEntityIPage, wrapper);
        List<AdminInfoEntity> adminInfoLists = result.getRecords();

        TableDataVO<AdminInfoEntity> dataVO = new TableDataVO<>();
        dataVO.setCode(200);
        dataVO.setMsg("");
        dataVO.setData(adminInfoLists);
        dataVO.setCount(result.getTotal());
        return dataVO;
        //之后需要配置拦截器
    }

    @Override
    public DataResult addAdminInfo(AdminInfoEntity adminInfo) {
        Integer count = adminInfoMapper.insert(adminInfo);
        if(count > 0){
            return  DataResult.success();
        }
        return DataResult.error();
    }

    @Override
    public DataResult updateAdminInfo(AdminInfoEntity adminInfo) {
        Integer count = adminInfoMapper.updateById(adminInfo);
        if(count > 0){
            return  DataResult.success();
        }
        return DataResult.error();
    }

    @Override
    public DataResult getRoleIdByUserId(Short userId) {
        Short result = authInfoMapper.getRoleIdByuserId(userId);
        return  DataResult.success(result);

    }

    @Override
    public DataResult GetAllAuthInfo() {
        List<AuthInfoEntity> authInfoEntities = authInfoMapper.GetAllAuthInfo();
        return DataResult.success(authInfoEntities);
    }

    @Override
    public DataResult getUserAuthList() {
        List<AuthInfoEntity> userAuthList = authInfoMapper.getUserAuthList();
        if(userAuthList != null){
            return DataResult.success(userAuthList);
        }
        return DataResult.error();
    }

    @Override
    public DataResult getRoleAuthChildrenList() {
        //获取所有角色
        List<Short> roleIds = userAuthMapper.selectList(null).stream().map(UserAuthEntity::getRoleId).collect(Collectors.toList());
        ArrayList<RoleToAuthResp> roleToAuthResp = new ArrayList(roleIds.size());
        for (Short roleId : roleIds) {
            UserAuthEntity userAuthEntity = userAuthMapper.selectOne(new QueryWrapper<UserAuthEntity>().eq("role_id", roleId));
            RoleToAuthResp roleToAuth = new RoleToAuthResp();
            roleToAuth.setRoleId(userAuthEntity.getRoleId());
            roleToAuth.setRoleName(userAuthEntity.getRoleName());
            roleToAuth.setRoleDesc(userAuthEntity.getRoleDesc());
            List<AuthInfoEntity> roleAuthListByauthIds = authInfoMapper.getRoleAuthListByRoleId(roleId);
            roleToAuth.setChildren(roleAuthListByauthIds);
            roleToAuthResp.add(roleToAuth);
        }
        return DataResult.success(roleToAuthResp);
    }

    @Override
    public DataResult deleteRoleAuth(Short roleId, Short authId) {
        authMenuMapper.delete(new QueryWrapper<AuthMenuEntity>().eq("role_id", roleId).eq("auth_id", authId));
        List<AuthInfoEntity> result = authInfoMapper.getRoleAuthListByRoleId(roleId);
        return DataResult.success(result);
    }

    @Override
    @Transactional
    public DataResult updateAuthMenu(Short roleId, Short[] authIds) {
        authMenuMapper.delete(new QueryWrapper<AuthMenuEntity>().eq("role_id", roleId));
        if(null == authIds || 0 == authIds.length){
            return DataResult.success("更新成功",null);
        }
        Integer result = authMenuMapper.insertAuthIds(roleId, authIds);
        if(result == authIds.length){
            return DataResult.success("更新成功",null);
        }
        return DataResult.error();
    }

    @Override
    public DataResult getRoleAuthChildrenListByRoleId(Short roleId) {
        List<AuthInfoEntity> result = authInfoMapper.getRoleAuthListByRoleId(roleId);
        ArrayList<AuthMenuResp> authMenuResps = new ArrayList<>();
        for (AuthInfoEntity authInfoEntity : result) {
            AuthMenuResp authMenuResp1 = new AuthMenuResp();
            authMenuResp1.setHidden("1");
            authMenuResp1.setAlwaysShow("1");
            authMenuResp1.setName(authInfoEntity.getAuthName());
            authMenuResp1.setPath(authInfoEntity.getPath());
            authMenuResp1.setComponent(authInfoEntity.getComponent());
            authMenuResp1.setMeta(new MetaVo(authInfoEntity.getAuthName(),authInfoEntity.getIcon()));
            List<AuthInfoEntity> children = authInfoEntity.getChildren();
            ArrayList<AuthMenuRespVo> authMenuRespCL = new ArrayList<>();
            for (AuthInfoEntity child : children) {
                AuthMenuRespVo authMenuResp2 = new AuthMenuRespVo();
                authMenuResp2.setHidden("1");
                authMenuResp2.setName(child.getAuthName());
                authMenuResp2.setPath(child.getPath());
                authMenuResp2.setComponent(child.getComponent());
                authMenuResp2.setMeta(new MetaVo(child.getAuthName(),child.getIcon()));
                authMenuRespCL.add(authMenuResp2);
            }
            authMenuResp1.setChildren(authMenuRespCL);
            authMenuResps.add(authMenuResp1);
        }

        return DataResult.success(authMenuResps);
    }

//    private List<Short> getMidByRid() {
//
//    }


}
